<script setup lang="ts">
import { reactive, ref } from 'vue'

import { useDebounceFn } from '@vueuse/core'
import { AgGridVue } from 'ag-grid-vue3'
import { Button, Card, Col, Form, FormItem, message, RangePicker, Row, Select, Spin } from 'ant-design-vue'

import { BillOrder } from '#/api/billOrder'
import { supplylList } from '#/api/supply'

import 'ag-grid-enterprise'

import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-quartz.css'
// 计算六个月前的日期
const today = new Date()
const sixMonthsAgo = new Date()
sixMonthsAgo.setMonth(today.getMonth() - 6)
// 格式化日期为YYYY-MM-DD
const formatDate = (date, isEndDate = false) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const time = isEndDate ? '23:59:59' : '00:00:00'
  return `${year}-${month}-${day}`
}

const form = reactive({
  supply_id: '',
  record_date: [formatDate(sixMonthsAgo), formatDate(today, true)],
})
const listData = ref([])
const gridRef = ref(null)
const Options = ref([])
const loading = ref(false)
const handleSupplySearch = useDebounceFn(async (keyword) => {
  loading.value = true
  try {
    const res = await supplylList({
      quick_search: keyword || '',
      page: 1,
      limit: 30,
      initKey: 'id',
      select: true,
    })

    Options.value = res.list.map((it: any) => ({ label: it.SupplyNa, value: it.id }))
  } finally {
    loading.value = false
  }
}, 300)

// 第一次打开下拉就触发一次空搜索，把全部选项拿回来
const handleSupplyDropdown = (open: any) => {
  if (open && Options.value.length === 0) {
    handleSupplySearch('')
  }
}

function initData() {
  if (!form.supply_id) {
    message.error('请选择供应商')
    return
  }
  const Params = {
    formData: { supplyId: form.supply_id, dateArr: form.record_date.join(',') },
  }
  spin.value = true
  BillOrder(Params)
    .then((response) => {
      listData.value = response
    })
    .finally(() => {
      spin.value = false
    })
}
const spin = ref(false)
const GridOptions: any = reactive({
  headerHeight: 30, // 设置表头高度
  rowHeight: 30, // 设置全局行高为50px
  enableRangeSelection: true,
  enableFillHandle: true, // 开启拖动复制
  suppressClearOnFillReduction: false, // 可选：控制填充行为
  defaultColDef: {
    editable: true, // 必须设置为可编辑，否则无法复制
  },
  suppressClickEdit: true, // 禁用单击即编辑
  rowDragManaged: true, // 启用托管拖拽
  columnDefs: [
    {
      headerName: '序号',
      maxWidth: 50,
      cellClass: 'borderCcc',
      cellStyle: { textAlign: 'center' },
      suppressMenu: true,
      suppressSorting: true,
      valueGetter: (params) => {
        // 当前在分页/排序/过滤后的顺序
        return params.node ? params.node.rowIndex + 1 : ''
      },
    },
    { headerName: '单据类型', field: 'orderTypeText', width: 120, cellDataType: 'text',cellClass: 'borderCcc', suppressMenu: true, cellStyle: { textAlign: 'center' },filter: 'agSetColumnFilter' },
    { headerName: '单据编号', field: 'recordSn', width: 150, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text', cellStyle: { textAlign: 'center' } },
    { headerName: '单据日期', field: 'date', width: 100, cellClass: 'borderCcc', cellDataType: 'text', suppressMenu: true, cellStyle: { textAlign: 'center' } },
    { headerName: '期初金额', field: 'qcPrice', width: 150, cellDataType: 'text', cellClass: 'borderCcc', suppressMenu: true, cellStyle: { textAlign: 'center' } },
    {
      headerName: '采购/委外/加工收料/入库',
      cellClass: 'borderCcc',
      cellStyle: { textAlign: 'center' },
      suppressMenu: true,
      children: [
        { headerName: '数量', field: 'inTotalNum', width: 100, cellClass: 'borderCcc',cellDataType: 'text',  suppressMenu: true, cellStyle: { textAlign: 'center' } },
        { headerName: '金额', field: 'inTotalAmount', width: 100, cellClass: 'borderCcc',cellDataType: 'text', suppressMenu: true, cellStyle: { textAlign: 'center' } },
        // { headerName: '加工费用', field: 'in_jg_price', width: 80, cellClass: 'borderCcc', suppressMenu: true, cellStyle: { textAlign: 'center' } },
      ],
    },
    {
      headerName: '采购/委外/加工退料/出库',
      cellClass: 'borderCcc',
      cellStyle: { textAlign: 'center' },
      suppressMenu: true,
      children: [
        { headerName: '数量', field: 'outTotalNum', width: 100, cellClass: 'borderCcc',cellDataType: 'text', suppressMenu: true, cellStyle: { textAlign: 'center' } },
        { headerName: '金额', field: 'outTotalAmount', width: 100, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text',  cellStyle: { textAlign: 'center' } },
        // { headerName: '加工费用', field: 'out_jg_price', width: 80, cellClass: 'borderCcc', suppressMenu: true, cellStyle: { textAlign: 'center' } },
      ],
    },

    { headerName: '记账调整金额', field: 'jztzAmount', width: 150, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text', cellStyle: { textAlign: 'center' } },
    { headerName: '付款金额', field: 'payPrice', width: 150, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text', cellStyle: { textAlign: 'center' } },
    { headerName: '费用金额', field: 'fyPrice', width: 150, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text', cellStyle: { textAlign: 'center' } },
    { headerName: '调整金额', field: 'tzPrice', width: 150, cellClass: 'borderCcc', suppressMenu: true,cellDataType: 'text', cellStyle: { textAlign: 'center' } },
    { headerName: '合计金额', field: 'hjPrice', width: 150, cellClass: 'borderCcc', suppressMenu: true, cellDataType: 'text',cellStyle: { textAlign: 'center' } },
    { headerName: '应付款', field: 'inPayPrice', width: 150, cellDataType: 'text', cellClass: 'borderCcc', suppressMenu: true, cellStyle: { textAlign: 'center' } },
    { headerName: '单据备注', field: 'remark', width: 400, cellClass: 'borderCcc',cellDataType: 'text', suppressMenu: true, cellStyle: { textAlign: 'center' } },
  ],
})
</script>
<template>
  <div>
    <Card size="small" style="margin: 20px">
      <Form :label-col="{ span: 7.5 }" style="margin-top: 20px">
        <Row :gutter="[15, 0]">
          <Col :span="6">
            <FormItem name="reqCode" label="供应商">
              <Select
                v-model:value="form.supply_id"
                show-search
                allow-clear
                style="width: 80%; height: 100%"
                placeholder="请输入"
                :filter-option="false"
                :options="Options"
                :loading="loading"
                @search="handleSupplySearch"
                @dropdown-visible-change="handleSupplyDropdown"
              />
            </FormItem>
          </Col>
          <Col :span="8">
            <FormItem name="reqCode" label="查询日期">
              <RangePicker :allow-clear="false" v-model:value="form.record_date" style="width: 80%" value-format="YYYY-MM-DD" />
            </FormItem>
          </Col>
          <Col :span="2">
            <Button type="primary" @click="initData()">搜索</Button>
          </Col>
        </Row>
      </Form>
    </Card>
    <Spin :spinning="spin">
      <Card size="small" style="margin: 20px">
        <AgGridVue ref="gridRef" :row-data="listData" :grid-options="GridOptions" class="ag-theme-quartz" style="height: 75vh; overflow-y: scroll; overflow-x: scroll" borderd />
      </Card>
    </Spin>
  </div>
</template>
<style scoped lang="scss">
// 设置ag-grid-table单元格边框

.custom-card {
  height: 100%;
  border-radius: 0 !important; /* 设置卡片的边角为直角 */
}

// 设置ag-grid-table单元格边框

:deep(.borderCcc) {
  // 表体单元格右边框
  border-right: 1px solid #ccc;
}
:deep(.ag-cell, .ag-full-width-row .ag-cell-wrapper.ag-row-group) {
  // 表体左右内边距
  padding: 0;
}

:deep(
//.ag-theme-balham .ag-header-cell-label,
//.ag-theme-alpine .ag-header-cell-label,
.ag-theme-quartz .ag-header-cell-label) {
  // 表头标题居中
  justify-content: center;
  display: flex;
  align-items: center;
}
:deep(.ag-header-cell, .ag-header-group-cell) {
  // 表头左右内边距
  padding: 0;
  border-right: 1px solid #ccc;
}
:deep(.ag-ltr .ag-header-viewport .ag-header-cell-resize::after) {
  // 表头右边框
  left: calc(100% - 3px);
}
:deep(.ag-header-cell-resize::after) {
  // 表头右边框
  width: 1px;
  height: 100%;
  top: 0;
}
</style>
